<template>
  <div id="docEditor" />
</template>

<script setup>
import { ref, onMounted, onBeforeMount, watch } from 'vue'
import { UAParser } from 'ua-parser-js'

import service from '@/utils/request'

const deviceType = ref(null)

const props = defineProps({
  fileId: {
    type: String,
    required: true,
  },
})

const config = ref(null)
const docEditor = ref(null)

const fetchConfig = async () => {
  const response = await service.get(`/onlyoffice/config/${props.fileId}`)
  config.value = response.data
  loadEditor()
}

const onDocumentReady = () => {
  console.log('document ready')
}

const onError = (error) => {
  console.log('document error', error)
}

const onRequestClose = () => {
  if (window.opener) {
    window.close()
    return
  }
  docEditor.value.destroyEditor()
}

const loadEditor = () => {
  if (!config.value) return
  docEditor.value = new window.DocsAPI.DocEditor('docEditor', {
    width: '100%',
    height: '100%',
    type: deviceType.value,
    documentType: config.value.documentType,
    ...config.value,
    events: {
      onDocumentReady,
      onError,
      onRequestClose,
    },
  })
}
onBeforeMount(() => {
  const parser = new UAParser(navigator.userAgent)
  const result = parser.getResult()
  deviceType.value = result.device.type === undefined ? 'desktop' : result.device.type
  console.log(deviceType.value)
})

onMounted(() => {
  fetchConfig()
})
watch(() => props.fileType, fetchConfig)
</script>
